﻿using Microsoft.Phone.Controls;
using Smile.Mvvm.Model;
using Smile.Mvvm.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace Smile.Mvvm.Service
{
    /// <summary>Service which manage page navigation.</summary>
    public class NavService : INavigationService
    {
        // @Public
        public void Navigate<TPage>()
        {
            var frame = Application.Current.RootVisual as PhoneApplicationFrame;
            if (frame == null)
            {
                return;
            }

            // Create page path.
            char[] separators = new char[] {'.'};
            var type = typeof(TPage);
            var pageData = typeof(TPage)
                .FullName.Split(separators, StringSplitOptions.RemoveEmptyEntries)
                .ToList();
            pageData.RemoveAt(0);
            string pagePath = "/";
            for (int i = 0; i < pageData.Count; ++i)
            {
                pagePath += "/" + pageData[i];
            }
            pagePath += ".xaml";

            frame.Navigate(new Uri(pagePath, UriKind.RelativeOrAbsolute));
        }

        public void GoBack()
        {
            // Get application frame.
            var frame = Application.Current.RootVisual as PhoneApplicationFrame;
            if (frame == null)
            {
                return;
            }

            // Go back action.
            if (frame.CanGoBack)
            {
                frame.GoBack();
            }
        }


        public void Reset()
        {
            // Get application frame.
            var frame = Application.Current.RootVisual as PhoneApplicationFrame;
            if (frame == null)
            {
                return;
            }

            // Reset action
            while (frame.BackStack.Any())
            {
                frame.RemoveBackEntry();
            }
        }
    }
}
